#!/usr/bin/env bash

# chkconfig:         2345 75 15
# description:       webssh

CUR_DIR="$(cd "$(dirname "${BASH_SOURCE-$0}")"; pwd)"
RUN_CMD="python main.py"
PID_FILE="/var/run/webssh.pid"
# PID_FILE="run/webssh.pid"

err_quit(){ if [ $1 -ne 0 ]; then echo $2; exit 1; fi;}

run(){
  [ -d logs ] || mkdir logs
  sh -c "$RUN_CMD"
}

start(){
  [ -d logs ] || mkdir logs
  [ -d "$(dirname "$PID_FILE")" ] || mkdir -p "$(dirname "$PID_FILE")"
  nohup sh -c "$RUN_CMD" >/dev/null 2>&1 &
  echo "$!" > "$PID_FILE"
  err_quit "$?" "启动服务失败"
}

stop(){
  pid="$(cat "$PID_FILE" 2>/dev/null)"
  if [ -z "$pid" ] ; then
    echo "服务未运行"
    return 1
  fi
	kill $pid 2>/dev/null
  printf "等待服务结束"
  for ((i=1; i <= 20; i++)); do
    if ps -p $pid >/dev/null; then
    printf "."
    sleep 1
    else
    printf "\n"
    break
    fi
  done
  if ps -p $pid > /dev/null ; then
    echo "开始强制结束服务"
    kill -9 $pid 2>/dev/null
  fi
  rm -f $PID_FILE
  echo "服务已结束"
}

status(){
  if [ -f "$PID_FILE" ] && kill -0 $(<"$PID_FILE") 2>/dev/null; then
    echo "服务运行中 pid=$(cat $PID_FILE)"
    return 0
  else
    echo "服务未运行"
    return 1
  fi
}

help(){
  echo "
用法: $0 [options] <params ...>

参数:

  -h , --help                   输出帮助信息

命令:

  run|(空)                      前台运行
  start                         开启服务
  stop                          结束服务
  restart                       重启服务
  status                        查看状态
  pip-install                   安装依赖
"
}

cd "$CUR_DIR"

case "$1" in
  run|"")
    run;;
  start)
    start;;
  stop)
    stop;;
  status)
    status
    exit $?;;
  pip-install)
    pip install -r requirements.txt -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com;;
  -h|--help)
    help;;
  *)
    echo "未知命令 "$1" 运行 $0 --help 查看帮助信息"
    exit 1;;
esac
